package cn.web03.controller;

import cn.web03.domain.Person;
import cn.web03.jpa.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PersonController {

    @Autowired
    PersonRepository personRepository;

    //分页查询
    @ResponseBody
    @GetMapping("/person/list")
    public Page<Person> getUserList(){
        Page<Person> personPage = personRepository.findAll(PageRequest.of(0, 10, Sort.Direction.DESC, "id"));
        personPage.getContent().forEach(p-> System.out.println(p.getName()));
        return personPage;
    }

    //添加数据
    @ResponseBody
    @GetMapping("/person/save")
    public int save(){
        // Long id, String name, Integer age, String address
        Person person = new Person(null, "零三", 18, "江西赣州");
        person.setSex((byte)1);
        Person save = personRepository.save(person);
         System.out.println(save);
        return 1;
    }
    // 删除数据

    @ResponseBody
    @GetMapping("/person/delete")
    public int delete(){
        personRepository.deleteById(1L);
        return 1;
    }
    //修改数据
    @ResponseBody
    @GetMapping("/person/update")
    public Person update(){
        Person person = new Person(2L, "零三", 10, "江西赣州");
        Person person1 = personRepository.saveAndFlush(person);
        return person1;
    }
}
